package com.alm.token.ui.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.BaseDialogBean;
import com.alm.token.ui.data.bean.EggPartnerIndexData;
import com.alm.token.ui.data.bean.MioOperatorAddOrderData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.SuperColorEggData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.fragmentDialog.NoticeDialogFragment;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.EggPartnerView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;

import java.util.ArrayList;
import java.util.List;

import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BuyMioOPRActivity extends BaseActivity implements EggPartnerView<EggPartnerIndexData> {


    @BindView(R.id.tv_totalmoney)
    TextView tvTotalmoney;
    @BindView(R.id.tv_paymoney)
    TextView tvPaymoney;
    @BindView(R.id.tv_buywarmshow)
    TextView tvBuywarmshow;
    @BindView(R.id.img_selectbizhong)
    ImageView imgSelectbizhong;
    @BindView(R.id.ly_ooutmoneybizhongtop)
    LinearLayout lyOoutmoneybizhongtop;

    @BindView(R.id.tv_buymsg)
    TextView tvBuymsg;
    @BindView(R.id.tv_buycommit)
    TextView tvBuycommit;

    @BindView(R.id.tv_mioblance)
    TextView tvMioblance;
    @BindView(R.id.tv_staue)
    TextView tvStaue;
    private List<EggPartnerIndexData.DataBean.GoodsBean> eggGoodsBeans = new ArrayList<>();
    private EggPartnerIndexData.DataBean dataBean;

    private int index = 0;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_buymioopr;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews() {
//        if (intentType == 1) {
        new ActionBarHelper(this).setTitle(getString(R.string.mioopr_hint_parnertitle));
//        tvBizhongtv.setText("");
        tvTotalmoney.setText("");
        imgSelectbizhong.setVisibility(View.INVISIBLE);
        tvBuymsg.setText("");
    }

    @Override
    protected void loadData() {
        ShowProgress();
        preenter.getMioOperatorOprIndexData();
    }


//    private CountDownTimer timer;
//    private long times = 0, refreshTime = -1;

    private void initView() {

        /**
         * "data": {
         *         "msg": "", // 信息
         *         "remainMioEx": 199950, // 剩余MIOex总数
         *         "mio": 98420.78566802,
         *         "goods": [
         *             {
         *                 "id": 1, // 产品id
         *                 "level": 1, // 级别
         *                 "mioPrice": 500, // 所需mio
         *                 "createTime": 1572420243000,
         *                 "updateTime": 1572434564000,
         *                 "status": 1, // 状态 1 可买 0 否
         *                 "num": 1000, // 总数
         *                 "remainNum": 999, // 剩余数量
         *                 "name": "500.00000000",
         *                 "startTime": 1572420248000, // 参与开始时间
         *                 "endTime": 1572765850000,
         *                 "joinMioNum": 500,
         *                 "mioExNum": 50 // 可获得的mioEx 数量
         *             }
         *         ]
         *     }
         */
        if (EmptyUtils.isNotEmpty(dataBean)) {
            tvMioblance.setText(CommonUtil.saveToPoint4WithNo(dataBean.getMio()));
            tvBuymsg.setText(EmptyUtils.isNotEmpty(dataBean.getMsg()) ? dataBean.getMsg() : "");


            if (dataBean.getBuyFlag() == 1) {
                tvPaymoney.setVisibility(View.GONE);
                tvTotalmoney.setText(dataBean.getLevelName());
                tvStaue.setText(getString(R.string.easteregg_hint_no));


                tvBuywarmshow.setText(Html.fromHtml(getString(R.string.mioopr_hint_hadbuyshow)
                        +"<font color=#653fac>"  + "\n" + dataBean.getLevelName() + "</font>"));
                imgSelectbizhong.setVisibility(View.INVISIBLE);
                lyOoutmoneybizhongtop.setOnClickListener(null);
                tvBuycommit.setText(getString(R.string.mioopr_hint_hadbuysucc));
                tvBuycommit.setBackground(getResources().getDrawable(R.drawable.shape_staking_item_nowgo_btnbgd_noopen));
                tvBuycommit.setOnClickListener(null);

                userMsgBean = new UserWalletData.DataBean.UserMsgBean();
                userMsgBean.setTitle(getString(R.string.common_warmprompt));
                userMsgBean.setEnTitle(getString(R.string.common_warmprompt));
                userMsgBean.setContent(getString(R.string.mioex_hint_warm2_buyone));
                userMsgBean.setEnContent(getString(R.string.mioex_hint_warm2_buyone));
                showCodeDialog();

            } else {
                if (eggGoodsBeans.size() > 0) {
                    tvPaymoney.setText(getString(R.string.mioopr_hint_needpaymoney) + eggGoodsBeans.get(index).getMioPrice() + "MIO");
                    tvTotalmoney.setText(eggGoodsBeans.get(index).getName());
                    imgSelectbizhong.setVisibility(eggGoodsBeans.size() > 1 ? View.VISIBLE : View.INVISIBLE);
                    tvStaue.setText(eggGoodsBeans.get(index).getStatus() == 1 && eggGoodsBeans.get(index).getRemainNum() >= 1 ? getString(R.string.easteregg_hint_yes) : getString(R.string.easteregg_hint_no));

                    lyOoutmoneybizhongtop.setOnClickListener(this);
                    tvBuycommit.setText(getString(R.string.easteregg_hint_nowapply));
                    tvBuycommit.setOnClickListener(this);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.ly_ooutmoneybizhongtop:
                if (EmptyUtils.isNotEmpty(eggGoodsBeans) && eggGoodsBeans.size() > 0) {//升级超级vip不可选择
                    showPopwindow();
                } else {
                    ShowProgress();
                    preenter.getMioOperatorOprIndexData();
                }
                break;

            case R.id.tv_buycommit:
                if (EmptyUtils.isNotEmpty(eggGoodsBeans) && eggGoodsBeans.size() > 0) {

                    userMsgBean = new UserWalletData.DataBean.UserMsgBean();
                    userMsgBean.setTitle(getString(R.string.common_warmprompt));
                    userMsgBean.setEnTitle(getString(R.string.common_warmprompt));

                    if (dataBean.getBuyFlag() == 1) {
                        userMsgBean.setContent(getString(R.string.mioex_hint_warm2_buyone));
                        userMsgBean.setEnContent(getString(R.string.mioex_hint_warm2_buyone));
                        showCodeDialog();
                        break;
                    }

                    if (eggGoodsBeans.get(index).getStartTime() > System.currentTimeMillis()) {
                        userMsgBean.setContent(getString(R.string.easteregg_hint_noopen));
                        userMsgBean.setEnContent(getString(R.string.easteregg_hint_noopen));
                        showCodeDialog();
                        break;
                    }

                    if (eggGoodsBeans.get(index).getRemainNum() <= 0) {
                        userMsgBean.setContent(getString(R.string.mioex_hint_warm1_full));
                        userMsgBean.setEnContent(getString(R.string.mioex_hint_warm1_full));
                        showCodeDialog();
                        break;
                    }

//                    UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
//                    sysMsgBean.setTitle(getString(R.string.common_warmprompt));
//                    sysMsgBean.setContent(getString(R.string.common_warmprompt_isbuy));
//                    DialogUtils.showInfor1(this, sysMsgBean, (pwd) -> {
                    preenter.getMioOperatorOprAddData(String.valueOf(eggGoodsBeans.get(index).getId()));
//                    });
                } else {
                    showToast(getString(R.string.common_loaderrritry));
                    ShowProgress();
                    preenter.getMioOperatorOprIndexData();
                }
                break;
        }
    }

    UserWalletData.DataBean.UserMsgBean userMsgBean;

    /***  弹出提示公告  ***/
    private void showCodeDialog() {
        NoticeDialogFragment dialogFragment = new NoticeDialogFragment();
        dialogFragment.setDialogBean(new BaseDialogBean("eggroal", userMsgBean));

        dialogFragment.setListener(new NoticeDialogFragment.ClickListener() {
            @Override
            public void Listener(String name, int potion) {
//                startActivity(BillActivity.class);
            }
        });

        dialogFragment.show(getSupportFragmentManager(), "NoticeDialogFragment");
        getFragmentManager().executePendingTransactions();
    }


    @Override
    public void getData(EggPartnerIndexData eggPartnerIndexData) {
        if (eggPartnerIndexData.getStatus() == 0) {

            if (EmptyUtils.isNotEmpty(eggPartnerIndexData.getData())) {
                eggGoodsBeans = eggPartnerIndexData.getData().getGoods();
                dataBean = eggPartnerIndexData.getData();
                if (EmptyUtils.isNotEmpty(eggGoodsBeans) && eggGoodsBeans.size() > 0) {
                    initView();
                } else {
                    tvBuycommit.setText(getString(R.string.easteregg_hint_noopen));
                    tvBuycommit.setOnClickListener(null);
                }
            } else {
                showToast(eggPartnerIndexData.getMsg());
            }
        } else {
            showToast(eggPartnerIndexData.getMsg());
        }
    }

    @Override
    public void getEggPartnerAddData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0) {
            finish();
        }
    }

    @Override
    public void getMioOperatorAddOrderData(MioOperatorAddOrderData mioOperatorAddOrderData) {

        /**
         * orderSn : MI157243544018
         * num : 500
         * moneyTypeName : MIO
         * moneyTypeIcon : https://api.iotoken.net/static/images/mio.png
         */

        if (mioOperatorAddOrderData.getStatus() == 0 && EmptyUtils.isNotEmpty(mioOperatorAddOrderData.getData())) {
            DialogUtils.enterPayPsw(this, (pwd1) -> {
                preenter.getMioOperatorPayOrderData(String.valueOf(mioOperatorAddOrderData.getData().getOrderSn()), pwd1);
            });
        } else {
            showToast(mioOperatorAddOrderData.getMsg());
        }
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
//        if (EmptyUtils.isNotEmpty(timer)) {
//            timer.cancel();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (EmptyUtils.isNotEmpty(timer)) {
//            timer.cancel();
//            timer = null;
//        }
    }

    PopupWindow popWindow;

    private void showPopwindow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.view_pop_selecter, null);
        LinearLayout ly_pop_body = popView.findViewById(R.id.ly_pop_body);

        if (EmptyUtils.isNotEmpty(eggGoodsBeans)) {
            for (int i = 0; i < eggGoodsBeans.size(); i++) {
                EggPartnerIndexData.DataBean.GoodsBean eggGoodsBean = eggGoodsBeans.get(i);

                /**
                 * "countDown": 86217, // 开启倒计时
                 * id : 1
                 * price : 10000
                 * totalNum : 3
                 * remainNum : 3
                 * getSmio : 10000
                 * createTime : 1557196757000
                 * updateTime : 1557198803000
                 * status : 1
                 * endTime : null
                 * name : 10000
                 * remark :
                 */


                View itemView = View.inflate(this, R.layout.item_pop_subscribeorder, null);
                ((TextView) itemView.findViewById(R.id.name)).setText(eggGoodsBean.getName());
                ((TextView) itemView.findViewById(R.id.money)).setText(String.valueOf(eggGoodsBean.getMioPrice()) + "MIO");
                int finalI = i;
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        index = finalI;
                        if (EmptyUtils.isNotEmpty(preenter)) {
                            ShowProgress();
                            preenter.getMioOperatorOprIndexData();
                        }
                        popWindow.dismiss();
                    }
                });
                ly_pop_body.addView(itemView);
            }
            ly_pop_body.setBackgroundColor(getResources().getColor(R.color.text_cccccc));
        }

        RelativeLayout outside = popView.findViewById(R.id.pop_outside);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, height);
            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
//        popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
        }
        outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

}
